package com.yonyou.brigade.third_parties.hcholiday.util;

import com.alibaba.fastjson.JSON;
import com.yonyou.brigade.third_parties.hcholiday.constant.HcHolidayAccessConstant;
import com.yonyou.brigade.third_parties.hcholiday.model.HcHolidayConfig;
import com.yonyou.brigade.third_parties.hcholiday.model.third.HcHolidayParamHead;
import com.yonyou.brigade.third_parties.hcholiday.model.third.HcHolidayRequestParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 签名生成工具类
 *
 * @author kangfw5
 * @date 2019-06-18
 */
public class HcHolidaySignUtil {
    /**
     * @param requestParam 花城请求参数
     * @param config       花城配置信息
     * @return 花城请求签名
     */
    public static String generateSign(HcHolidayRequestParam requestParam, HcHolidayConfig config) {
        HcHolidayParamHead head = requestParam.getHead();
        Map<String, Object> signMap = JSON.parseObject(JSON.toJSONString(head));
        signMap.put(HcHolidayAccessConstant.HEAD_SECRET_KEY, config.getSecretKey());
        if (requestParam.getData() != null) {
            signMap.put(HcHolidayRequestParam.DATA, JSON.toJSONString(requestParam.getData()));
        }
        List<String> keyList = new ArrayList<>(signMap.keySet());
        keyList.remove(HcHolidayAccessConstant.HEAD_SIGN);
        Collections.sort(keyList);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < keyList.size(); i++) {
            String key = keyList.get(i);
            if (StringUtils.isEmpty(String.valueOf(signMap.get(key)))) {
                continue;
            }
            sb.append(key).append('=').append(signMap.get(key));
            if (i != keyList.size() - 1) {
                sb.append('&');
            }
        }
        return DigestUtils.md5DigestAsHex(sb.toString().getBytes()).toUpperCase();
    }
}
